package com.ckh.springboot.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ckh.springboot.common.Constants;
import com.ckh.springboot.common.Result;
import com.ckh.springboot.controller.dto.UserPasswordDTO;
import com.ckh.springboot.entity.JoinClass;
import com.ckh.springboot.entity.StudentClock;
import com.ckh.springboot.entity.SysClass;
import com.ckh.springboot.entity.User;
import com.ckh.springboot.mapper.UserMapper;
import com.ckh.springboot.service.IJoinClassService;
import com.ckh.springboot.service.IStudentClockService;
import com.ckh.springboot.service.ISysClassService;
import com.ckh.springboot.service.IUserService;
import com.ckh.springboot.vo.GetClassInfoVo;
import com.ckh.springboot.vo.StudentClockInVo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ckh
 * @since 2022-04-04
 */
@RestController
@RequestMapping("/api/sysClass")
@CrossOrigin(origins = "http://localhost:9528")
public class SysClassController {


    @Resource
    private ISysClassService sysClassService;

    @Resource
    private IJoinClassService joinClassService;

    @Resource
    private IStudentClockService studentClockService;

    /**
     * Description: a
     * 查询学生是否打卡列表
     * @author: luoCan
     */
    @GetMapping("/getStudentClockList")
    public Result getStudentClockList(@RequestParam Integer userId) {
        List<StudentClock> list1 = studentClockService.list(Wrappers.<StudentClock>lambdaQuery().eq(StudentClock::getUserId, userId));
        for (StudentClock studentClock : list1) {
            SysClass one = sysClassService.getOne(Wrappers.<SysClass>lambdaQuery().eq(SysClass::getId, studentClock.getClassId()));
            studentClock.setClassName(one.getName());
        }
        return Result.success(list1);
    }

    /**
     * 创建班级
     * @return
     */
    @PostMapping("/createClass")
    public Result save(@RequestBody SysClass sysClass) {
        //根据班级名称和秘钥查询班级是否存在
        SysClass one = sysClassService.getOne(Wrappers.<SysClass>lambdaQuery().eq(SysClass::getName, sysClass.getName())
                .eq(SysClass::getClassKey, sysClass.getClassKey()));
        if(ObjectUtils.isNotEmpty(one)){
                return Result.error(Constants.CODE_400, "班级已存在!");
        }
        //创建班级
        return Result.success(sysClassService.save(sysClass));
    }

    /**
     * 查询班级列表(包含名字，密钥，学生信息)
     * @return
     */
    @GetMapping("/getClassInfo")
    public Result getClassInfo(@RequestParam Integer userId) {
        List<GetClassInfoVo> getClassInfoVo = new ArrayList<>();
        //根据教师id查询创建的
        List<SysClass> list = sysClassService.list(Wrappers.<SysClass>lambdaQuery().eq(SysClass::getUserId, userId));
        for (SysClass sysClass : list) {
            GetClassInfoVo getClassInfoVo2 = new GetClassInfoVo();
            getClassInfoVo2.setClassId(sysClass.getId());
            getClassInfoVo2.setClassKey(sysClass.getClassKey());
            getClassInfoVo2.setClockStatus(sysClass.getClockStatus());
            getClassInfoVo2.setClockTime(sysClass.getClockTime());
            getClassInfoVo2.setCreateTime(sysClass.getCreateTime());
            getClassInfoVo2.setName(sysClass.getName());
            getClassInfoVo2.setUserId(sysClass.getUserId());

            List<User> classInfo = sysClassService.getClassInfo(sysClass.getId());
            if(ObjectUtils.isNotEmpty(classInfo) && ObjectUtils.isNotNull(classInfo.get(0))){
                getClassInfoVo2.setUserList(classInfo);
            }
            getClassInfoVo.add(getClassInfoVo2);
        }
        if(ObjectUtils.isEmpty(getClassInfoVo)){
            return Result.success();
        }
        return Result.success(getClassInfoVo);
    }

    /**
     * 发布打卡
     * @return
     */
    @PostMapping("/clockIn")
    public Result clockIn(@RequestBody SysClass sysClass) throws ParseException {
        SysClass one = sysClassService.getOne(Wrappers.<SysClass>lambdaQuery().eq(SysClass::getId, sysClass.getId()));
        if(ObjectUtils.isEmpty(one)){
            return Result.error(Constants.CODE_400, "班级不存在!");
        }

        if(ObjectUtils.isNotEmpty(one.getClockTime())){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date1 = sdf.format(one.getClockTime());
            String date2 = sdf.format(new Date());
            if (date1.equals(date2)) {
                return Result.error(Constants.CODE_400, "该班级今日已发布打卡!");
            }
        }
        //根据班级名称和秘钥查询班级是否存在
        sysClass.setClockStatus(1);
        sysClass.setClockTime(new Date());

        List<JoinClass> list = joinClassService.list(Wrappers.<JoinClass>lambdaQuery().eq(JoinClass::getClassId, sysClass.getId()));
        for (JoinClass joinClass : list) {
            StudentClock studentClock = new StudentClock();
            studentClock.setUserId(joinClass.getUserId());
            studentClock.setClassId(sysClass.getId());
            studentClock.setClockStatus(0);
            studentClock.setReleaseTime(new Date());
            studentClockService.save(studentClock);
        }



        return Result.success(sysClassService.updateById(sysClass));
    }


    /**
     * 定时任务每天凌晨刷新发布状态
     */
    @Scheduled(cron = "0 0 0 * * ?")
//	@GetMapping("/test")
    public void shareReCheckPooling() {
        sysClassService.updateClockStatus();
    }


    /**
     * 学生班级打卡
     * @return
     */
    @PostMapping("/studentClockIn")
    public Result studentClockIn(@RequestBody StudentClockInVo studentClockInVo) throws ParseException {
        //判断学生是否在本班级
        JoinClass one1 = joinClassService.getOne(Wrappers.<JoinClass>lambdaQuery().eq(JoinClass::getUserId, studentClockInVo.getUserId())
                .eq(JoinClass::getClassId, studentClockInVo.getClassId()));
        if(ObjectUtils.isEmpty(one1)){
            return Result.error(Constants.CODE_400, "您不在班级内，请先加入班级!");
        }

        //判断学生今日在本班级是否打卡
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date1 = sdf.format(new Date());
        StudentClock one = studentClockService.getOne(Wrappers.<StudentClock>lambdaQuery().eq(StudentClock::getClassId, studentClockInVo.getClassId())
                .eq(StudentClock::getUserId, studentClockInVo.getUserId())
                .like(StudentClock::getReleaseTime, date1));
        if(ObjectUtils.isNotEmpty(one.getClockTime())){
            return Result.error(Constants.CODE_400, "您今日该班级已打卡,请勿重复打卡!");
        }

        //保存打卡
//        StudentClock studentClock = new StudentClock();
//        studentClock.setUserId(studentClockInVo.getUserId());
//        studentClock.setClassId(studentClockInVo.getClassId());
//        studentClock.setClockStatus(studentClockInVo.getStatus());
//        studentClock.setClockTime(new Date());

        one.setClockStatus(1);
        one.setClockTime(new Date());
        return Result.success(studentClockService.updateById(one));
    }

    /**
     * 后台班级管理列表
     * @return
     */
    @PostMapping("/studentList")
    public Result studentList(@RequestBody StudentClockInVo studentClockInVo) throws ParseException {
        //判断学生是否在本班级
        JoinClass one1 = joinClassService.getOne(Wrappers.<JoinClass>lambdaQuery().eq(JoinClass::getUserId, studentClockInVo.getUserId())
                .eq(JoinClass::getClassId, studentClockInVo.getClassId()));
        if(ObjectUtils.isEmpty(one1)){
            return Result.error(Constants.CODE_400, "您不在班级内，请先加入班级!");
        }

        //判断学生今日在本班级是否打卡
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date1 = sdf.format(new Date());
        StudentClock one = studentClockService.getOne(Wrappers.<StudentClock>lambdaQuery().eq(StudentClock::getClassId, studentClockInVo.getClassId())
                .eq(StudentClock::getUserId, studentClockInVo.getUserId())
                .like(StudentClock::getReleaseTime, date1));
        if(ObjectUtils.isNotEmpty(one.getClockTime())){
            return Result.error(Constants.CODE_400, "您今日该班级已打卡,请勿重复打卡!");
        }

        //保存打卡
//        StudentClock studentClock = new StudentClock();
//        studentClock.setUserId(studentClockInVo.getUserId());
//        studentClock.setClassId(studentClockInVo.getClassId());
//        studentClock.setClockStatus(studentClockInVo.getStatus());
//        studentClock.setClockTime(new Date());

        one.setClockStatus(1);
        one.setClockTime(new Date());
        return Result.success(studentClockService.updateById(one));
    }

    /**
     * Description:a
     * 后台获取班级管理列表
     * @param null:
     * @author: luoCan
     */
    @GetMapping("/getSysClassList")
    public Result getSysClassList(String name,
                              @RequestParam Integer pageNum,
                              @RequestParam Integer pageSize) {
        Page<SysClass> page = sysClassService.getSysClassList(new Page<>(pageNum, pageSize), name);
        for (SysClass record : page.getRecords()) {
            long count = joinClassService.count(Wrappers.<JoinClass>lambdaQuery().eq(JoinClass::getClassId, record.getId()));
            record.setPeopleNum(count);
        }
        return Result.success(page);
    }

    /**
     * Description:a
     * 后台班级管理删除
     * @param null:
     * @author: luoCan
     */
    @PostMapping("/deleteSysClass")
    public Result deleteSysClass(@RequestBody SysClass sysClass) {
        return Result.success(sysClassService.removeById(sysClass));
    }

    /**
     * Description:a
     * 后台签到记录管理删除
     * @param null:
     * @author: luoCan
     */
    @PostMapping("/deleteStudentClock")
    public Result deleteStudentClock(@RequestBody StudentClock studentClock) {
        return Result.success(studentClockService.removeById(studentClock));
    }


    /**
     * Description:a
     * 后台签到记录管理列表
     * @param null:
     * @author: luoCan
     */
    @GetMapping("/getStudentClockListPage")
    public Result getStudentClockList(String name,
                                      @RequestParam Integer pageNum,
                                      @RequestParam Integer pageSize,
                                      Integer teacherId,
                                      Integer userId) {
        // 管理员：不传teacherId/userId，查全部
        // 老师：传teacherId，查自己班级学生
        // 学生：传userId，只查自己
        // 具体实现需在service层处理
        return Result.success(studentClockService.getStudentClockList(new Page<>(pageNum, pageSize), name, teacherId, userId));
    }


}

